package com.instpower.things.instpower;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName HandlerManager
 * @Author: hellmash@gmail.com
 * @Date: 2020/3/5
 * @Version: 1.0.0
 * @Description: 协议处理管理
 */
public class HandlerManager {
    private Map<String, Handler> mHandlers = null;
    private static HandlerManager mInstance = null;

    private HandlerManager() {
        mHandlers = new HashMap<>();
    }

    public static HandlerManager getInstance() {
        if (mInstance == null) {
            mInstance = new HandlerManager();
        }
        return mInstance;
    }

    /**
     * 查找对应的协议处理器
     * @param handlerId
     * @return
     */
    public Handler find(short handlerId) {
        return mHandlers.get(String.format("CMD%04d", handlerId));
    }

    public void register(Class<?> clazz) {
        try {
            Handler handler = (Handler) clazz.newInstance();
            mHandlers.put(String.format("CMD%04d",handler.getId()), handler);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void register(Handler handler) {
        mHandlers.put(String.format("CMD%04d",handler.getId()), handler);
    }
}
